$(function(){
	InitLeftMenu();
	tabClose();
	tabCloseEven();
	clockon();
});
function empty(value){
	if (value == null || value == "" || value == "0" || value == "undefined" || value == undefined || value == "null" || value == "(null)" || value == 'NULL' || typeof (value) == 'undefined' || Object.keys(value).length === 0)
	{
		return true;
	}
	else
	{
		value = value + "";
		value = value.replace(/\s/g, "");
		if (value == "")
		{
			return true;
		}
		return false;
	}
}

(function(window){
	var u = {};
	u.get=function(key){
		if(empty(key)) return false;
		let item = JSON.parse(window.localStorage.getItem(key));
		if (item && item.expired >= Date.now() ) {
			return item.value;
		}else{
			window.localStorage.removeItem(key);
			return false;
		}
	};
	u.set=function(key, value, expired){
		let item = {value: value};
		expired = expired ? expired : 60;
		item.expired = Date.now() + 1000 * expired;
		item.value = value;
		return window.localStorage.setItem(key, JSON.stringify(item));
	};
	window.storage = u;
})(window);

//初始化左侧
function InitLeftMenu() {
	$('.navMenu li a').click(function(){
		var tabTitle = $(this).attr("title");
		var url = $(this).attr("href");
		addTab(tabTitle,url);
		$('.navMenu li').removeClass("active");
		$(this).parent().addClass("active");
		return false;
	}).hover(function(){
		$(this).parent().addClass("hover");
	},function(){
		$(this).parent().removeClass("hover");
	});
}

function addTab(subtitle,url){
	if(!$('#rightTabs').tabs('exists',subtitle)){
		$('#rightTabs').tabs('add',{
			title:subtitle,
			href :url,
			closable:true,
			width:$('#rightTabs').width()-10,
			height:$('#rightTabs').height()-26
		});
	}else{
		$('#rightTabs').tabs('select',subtitle);
	}
	tabClose();
}
function tabClose()
{
	/*双击关闭TAB选项卡*/
	$(".tabs-inner").dblclick(function(){
		var subtitle = $(this).children("span").text();
		if(subtitle !='首页')$('#rightTabs').tabs('close',subtitle);
	})

	$(".tabs-inner").bind('contextmenu',function(e){
		$('#mm').menu('show', {
			left: e.pageX,
			top: e.pageY,
		});

		var subtitle =$(this).children("span").text();
		$('#mm').data("currtab",subtitle);

		return false;
	});
}
//绑定右键菜单事件
function tabCloseEven()
{
	//关闭当前
	$('#mm-tabclose').click(function(){
		var currtab_title = $('#mm').data("currtab");
		if(currtab_title!='首页')$('#rightTabs').tabs('close',currtab_title);
	})
	//全部关闭
	$('#mm-tabcloseall').click(function(){
		$('.tabs-inner span').each(function(i,n){
			var t = $(n).text();
			if(t!='首页')$('#rightTabs').tabs('close',t);
		});
	});
	//关闭除当前之外的TAB
	$('#mm-tabcloseother').click(function(){
		var currtab_title = $('#mm').data("currtab");
		$('.tabs-inner span').each(function(i,n){
			var t = $(n).text();
			if(t!=currtab_title)
				$('#rightTabs').tabs('close',t);
		});
	});
	//关闭当前右侧的TAB
	$('#mm-tabcloseright').click(function(){
		var nextall = $('.tabs-selected').nextAll();
		if(nextall.length==0){
			msgShow('系统提示','后边没有啦~~','warning');
			//alert('后边没有啦~~');
			return false;
		}
		nextall.each(function(i,n){
			var t=$('a:eq(0) span',$(n)).text();
			$('#rightTabs').tabs('close',t);
		});
		return false;
	});
	//关闭当前左侧的TAB
	$('#mm-tabcloseleft').click(function(){
		var prevall = $('.tabs-selected').prevAll();
		if(prevall.length==0){
			msgShow('系统提示','到头了，前边没有啦~~','warning');
			return false;
		}
		prevall.each(function(i,n){
			var t=$('a:eq(0) span',$(n)).text();
			$('#rightTabs').tabs('close',t);
		});
		return false;
	});

	//退出
	$("#mm-exit").click(function(){
		$('#mm').menu('hide');
	});
}

//弹出信息窗口 title:标题 msgString:提示信息 msgType:信息类型 [error,info,question,warning]
function msgShow(title, msgString, msgType) {
	$.messager.alert(title, msgString, msgType);
}
function clockon() {
    var now = new Date();
    var year = now.getFullYear(); //getFullYear getYear
    var month = now.getMonth();
    var date = now.getDate();
    var day = now.getDay();
    var hour = now.getHours();
    var minu = now.getMinutes();
    var sec = now.getSeconds();
    var week;
    month = month + 1;
    if (month < 10) month = "0" + month;
    if (date < 10) date = "0" + date;
    if (hour < 10) hour = "0" + hour;
    if (minu < 10) minu = "0" + minu;
    if (sec < 10) sec = "0" + sec;
    var arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
    week = arr_week[day];
    var time = "";
	if  ( day==0 )  time="<font class=\"up-font-over\">";
    if  ( day > 0 && day < 6 )  time="<font class=\"up-fonts\">";
    if  ( day==6 )  time="<font class=\"up-font-over\">";
    time+= year + "年" + month + "月" + date + "日" + " " + hour + ":" + minu + ":" + sec + " " + week;
	time+="</font>"

    $("#localtime").html(time);

    var timer = setTimeout("clockon()", 200);
}

/*
** randomWord 产生任意长度随机字母数字组合
** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
** xuanfeng 2014-08-28
*/

function randStr(length){
    var str = "",
        //arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    var len = arr.length-1;
    for(var i=0; i<length; i++){
        let pos = Math.round(Math.random() * len);
        str += arr[pos];
    }
    return str;
}

var clearCache= function(){
	$.messager.confirm('提示','确定要清除缓存吗？',function(r){
		if(r==true){
			$.messager.progress();
			$.post('/admin/index/clearCache', {}, function(data){
				$.messager.progress('close');
				if(data.ret==0){
					$.messager.show({
						title:'提示',
						msg:data.msg,
						timeout:3000,
						showType:'slide'
					});
				}else{
					$.messager.alert('提示',data.msg,'warning');
				}
			},'json');
		}
	});
};
var logout= function(){
	window.location.replace('/public/logout');
};
var adminlogout= function(){
	window.location.replace('/admin/index/logout');
};

var qiniu_upload = function(file, complete, token, error, progress) {
	var finishedAttr = [];
	var compareChunks = [];
	var observable;
	if (file) {
		var key = (new Date()).valueOf().toString() + Math.random().toString().slice(2, 10) + '.jpg';
		//var key = null;
		var config = {
			useCdnDomain: true,
			region: qiniu.region.z2,//华东
		};
		var putExtra = {
			fname: "",
			params: {},
			mimeType: ["image/png", "image/jpg", "image/jpeg", "image/gif", "video/mp4"]
		};

		token = empty(token) ? storage.get('qiniuToken') : token;
		if (empty(token)) {
			$.ajax({
				type: 'POST',
				url: '/main/uptoken',
				async: false,
				dataType: 'json',
				success: function (data) {
					token = data.uptoken;
					storage.set('qiniuToken', token, 3600);
				},
				error: function () {
					$.messager.alert('提示', '获取上传token失败', 'warning');
				}
			});
		}
		if (typeof (error) !== 'function') {
			error = function (err) {
				console.log(JSON.stringify(err));
			};
		}

		if (typeof (progress) != 'function') {
			next = function (response) {
				var chunks = response.chunks || [];
				var total = response.total;
				// 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
				for (var i = 0; i < chunks.length; i++) {
					if (chunks[i].percent === 0 || finishedAttr[i]) {
						continue;
					}
					if (compareChunks[i].percent === chunks[i].percent) {
						continue;
					}
					if (chunks[i].percent === 100) {
						finishedAttr[i] = true;
					}
				}
				//console.log(total.percent);
				compareChunks = chunks;
			};
		}

		observable = qiniu.upload(file, key, token, putExtra, config);
		var subscription = observable.subscribe(next, error, complete);//控制句柄
	}
};
var qiniu_single = function(uploader, complete) {
	$('#'+uploader).click(function () {
		let input = document.createElement('input');
		input.type = 'file';
		input.style.opacity = '0';
		input.accept = "image/*"
		input.onchange = function () {
			qiniu_upload(this.files[0], function (res) {
				complete(indexVm.domain + res.key);
			});
			$(input).remove();
		};
		document.body.append(input);
		$(input).trigger('click');
	});
};
var qiniu_multiple = function(uploader, complete) {
	$('#'+uploader).click(function () {
		let input = document.createElement('input');
		input.type = 'file';
		input.style.opacity = '0';
		input.multiple = "multiple";
		input.accept = "image/*"
		input.onchange = function () {
			for(let i=0;item=this.files[i++];){
				qiniu_upload(item, function (res) {
					complete(indexVm.domain + res.key);
				});
			}
			$(input).remove();
		};
		document.body.append(input);
		$(input).trigger('click');
	});
};

var getTreeChecked = function(obj){
	var nodes = $(obj).tree('getChecked');
	var s = '';
	for(var i=0; i<nodes.length; i++){
		if (s !== ''){ s += ','; }
		s += nodes[i].id;
	}
	return s;
};

function fixWidth(percent)
{
	return parseInt(($(window).width() - $(".leftmenu").width() - 13) * percent / 100) - 30;//datagrid总宽度 * 百分比 - 左右padding15像素
}
function fixWidth1(percent)
{
	return parseInt(($(window).width() - $(".leftmenu").width() - 180) * percent / 100) - 30;//datagrid总宽度 * 百分比 - 左右padding15像素
}
